#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

typedef struct student{
    int id;
    char name[45];
    int age;
}Student;

int main(){
    int fd = open("test.txt",O_CREAT|O_RDWR|O_TRUNC,0644);
    if (fd == -1){
        perror("open error");
        exit(1);
    }
    Student stu = {11,"张三",18};
    Student *p;
    int len = sizeof(stu);
    printf("len = %d\n",len);
    ftruncate(fd,len);

    p = mmap(NULL,len,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    if (p == MAP_FAILED){
        perror("mmap error");
        exit(1);
    }
    memcpy(p,&stu,len);
    printf("id=%d,name=%s,age=%d\n",p->id,p->name,p->age);//直接读
    close(fd);//关闭打开的文件
    int ret = munmap(p,len);
    if (ret == -1){
        perror("munmap error");
        exit(0);
    }
    return 0;
}